import { _decorator, CCFloat, Component, Node, UITransform, v3, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

enum RodState {
    falling,
    rising

}

@ccclass('FishingRod')
export class FishingRod extends Component {

    @property({ type: CCFloat, displayName: '重量' })
    public weight: number = 100;

    @property({ type: CCFloat, displayName: '拉力' })
    public force: number = 200;

    @property({ type: CCFloat, displayName: '最大速度' })
    maxSpeed: number = 1000;

    @property
    bounceRatio: number = 0.8;

    acceleration: number = 0;      //当前速度

    state: RodState = RodState.falling;

    _pos = v3();

    start() {
        this.acceleration = 0;
        this.state = RodState.falling;
        this._pos.set(this.node.position);
    }

    changeState(b: boolean) {
        if (b) {
            this.state = RodState.rising;
        }
        else {
            this.state = RodState.falling;
        }
    }

    update(deltaTime: number) {
        switch (this.state) {
            case RodState.falling:
                this.acceleration -= deltaTime * this.weight;
                break;
            case RodState.rising:
                this.acceleration += deltaTime * this.force;
                break;
        }
        this._pos.y = this.node.position.y + this.acceleration;
        this.node.position = this._pos;
        console.log(this.node.position, this._pos);
        this.bounce();
    }



    bounce() {
        const ui = this.node.getComponent(UITransform)
        const rect = ui.getBoundingBox();

        const parentUI = this.node.parent.getComponent(UITransform)
        const parentRect = parentUI.getBoundingBox();

        if (rect.yMax >= parentRect.yMax) {
            this._pos.y = parentRect.yMax - ui.height / 2 - 0.01;
            this.node.position = this._pos;
            this.acceleration = -Math.abs(this.acceleration * this.bounceRatio);
        }
        else if (rect.yMin <= parentRect.yMin) {
            this._pos.y = parentRect.yMin + ui.height / 2 + 0.01;
            this.node.position = this._pos;
            this.acceleration = Math.abs(this.acceleration * this.bounceRatio);
        }
    }

}


